package cn.com.blueInfo.bpm.person.repository.impl;

import cn.com.blueInfo.bpm.common.entity.BaseEntity;
import cn.com.blueInfo.bpm.common.enums.BaseDeleted;
import cn.com.blueInfo.bpm.common.repository.BaseRepository;
import cn.com.blueInfo.bpm.person.entity.Organization;
import cn.com.blueInfo.bpm.person.enums.OrganizationTreeType;
import cn.com.blueInfo.bpm.person.mapper.OrganizationMapper;
import cn.com.blueInfo.bpm.person.repository.OrganizationRepository;
import cn.com.blueInfo.bpm.person.request.OrganizationDTO;
import cn.com.blueInfo.core.entity.CurrentLoginUserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 组织结构信息表 数据服务实现类
 * @author suxch
 * @since 2025-09-01 19:28:09
 */
@Log4j2
@Service
public class OrganizationRepositoryImpl
        extends ServiceImpl<OrganizationMapper, Organization>
        implements OrganizationRepository, BaseRepository<Organization, OrganizationDTO.QueryDTO> {

    @Autowired
    private CurrentLoginUserInfo currentLoginUserInfo;

    /**
     * 提供获取 CurrentLoginUserInfo 的方法（由实现类提供，避免接口中注入）
     * @return CurrentLoginUserInfo
     */
    @Override
    public CurrentLoginUserInfo getCurrentLoginUserInfo() {
        return currentLoginUserInfo;
    }

    /**
     * 新增组织结构信息
     * @param organization 组织结构信息参数
     */
    @Override
    public Integer createOrganization(Organization organization) {
        return sqlExecuteResult(save(organization));
    }

    /**
     * 批量新增组织结构信息
     * @param organizationList 组织结构信息参数列表
     */
    @Override
    public Integer batchCreateOrganization(List<Organization> organizationList) {
        return sqlExecuteResult(saveBatch(organizationList), organizationList.size());
    }

    /**
     * 删除组织结构信息
     * @param organizationId 组织结构信息ID
     */
    @Override
    public Integer deleteOrganization(Long organizationId) {
        Organization organization = new Organization();
        organization.setId(organizationId);
        organization.setDeleted(BaseDeleted.DELETED);
        return sqlExecuteResult(removeById(organization));
    }

    /**
     * 批量删除组织结构信息
     * @param organizationIdList 组织结构信息ID列表
     */
    @Override
    public Integer batchDeleteOrganization(List<Long> organizationIdList) {
        List<Organization> organizationList = new ArrayList<>();
        for (Long organizationId : organizationIdList) {
            Organization organization = new Organization();
            organization.setId(organizationId);
            organization.setDeleted(BaseDeleted.DELETED);
        }
        return sqlExecuteResult(removeBatchByIds(organizationList), organizationList.size());
    }

    /**
     * 更新部分组织结构信息
     * @param organization 组织结构信息参数
     */
    @Override
    public Integer updateOrganizationPartial(Organization organization) {
        validateUpdateId(organization.getId());
        LambdaUpdateWrapper<Organization> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Organization::getId, organization.getId());
        return sqlExecuteResult(update(updateWrapper));
    }

    /**
     * 更新全部组织结构信息
     * @param organization 组织结构信息参数
     */
    @Override
    public Integer updateOrganization(Organization organization) {
        validateUpdateId(organization.getId());
        return sqlExecuteResult(updateById(organization));
    }

    /**
     * 查询一条组织结构信息
     * @param organizationId 组织结构信息ID
     */
    @Override
    public Organization getOrganizationById(Long organizationId) {
        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Organization::getId, organizationId);
        return getOne(queryWrapper);
    }

    /**
     * 分页查询组织结构信息
     * @param organizationQueryDTO 组织结构信息参数
     */
    @Override
    public Page<Organization> getOrganizationPage(OrganizationDTO.QueryDTO organizationQueryDTO) {
        Page<Organization> organizationPage = new Page<>(
                organizationQueryDTO.getPage(), organizationQueryDTO.getSize());
        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, organizationQueryDTO);

        BaseDeleted deleted = organizationQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeletePage(organizationPage, queryWrapper);
        } else {
            return page(organizationPage, queryWrapper);
        }
    }

    /**
     * 根据条件查询 组织结构信息 数量
     * @param organizationQueryDTO 组织结构信息参数
     */
    @Override
    public Long getOrganizationCount(OrganizationDTO.QueryDTO organizationQueryDTO) {
        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, organizationQueryDTO);

        BaseDeleted deleted = organizationQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeleteCount(queryWrapper);
        } else {
            return count(queryWrapper);
        }
    }

    /**
     * 根据条件查询 组织结构信息
     * @param organizationQueryDTO 组织结构信息参数
     */
    @Override
    public List<Organization> getOrganizationList(OrganizationDTO.QueryDTO organizationQueryDTO) {
        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, organizationQueryDTO);

        BaseDeleted deleted = organizationQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeleteList(queryWrapper);
        } else {
            return list(queryWrapper);
        }
    }

    private void queryWrapper(LambdaQueryWrapper<Organization> queryWrapper,
                              OrganizationDTO.QueryDTO organizationQueryDTO) {

        Long orgLevelId = organizationQueryDTO.getOrgLevelId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(orgLevelId), Organization::getOrgLevelId, orgLevelId);

        String levelPath = organizationQueryDTO.getLevelPath();
        queryWrapper.eq(StringUtils.isNotBlank(levelPath), Organization::getLevelPath, levelPath);

        String orgCode = organizationQueryDTO.getOrgCode();
        queryWrapper.eq(StringUtils.isNotBlank(orgCode), Organization::getOrgCode, orgCode);

        String orgName = organizationQueryDTO.getOrgName();
        queryWrapper.eq(StringUtils.isNotBlank(orgName), Organization::getOrgName, orgName);

        String orgShortName = organizationQueryDTO.getOrgShortName();
        queryWrapper.eq(StringUtils.isNotBlank(orgShortName), Organization::getOrgShortName, orgShortName);

        String orgCategory = organizationQueryDTO.getOrgCategory();
        queryWrapper.eq(StringUtils.isNotBlank(orgCategory), Organization::getOrgCategory, orgCategory);

        Long parentId = organizationQueryDTO.getParentId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(parentId), Organization::getParentId, parentId);

        String orgPathId = organizationQueryDTO.getOrgPathId();
        queryWrapper.eq(StringUtils.isNotBlank(orgPathId), Organization::getOrgPathId, orgPathId);

        String orgPathCn = organizationQueryDTO.getOrgPathCn();
        queryWrapper.eq(StringUtils.isNotBlank(orgPathCn), Organization::getOrgPathCn, orgPathCn);

        String description = organizationQueryDTO.getDescription();
        queryWrapper.eq(StringUtils.isNotBlank(description), Organization::getDescription, description);

        OrganizationTreeType treeType = organizationQueryDTO.getTreeType();
        queryWrapper.eq(ObjectUtils.isNotEmpty(treeType), Organization::getTreeType, treeType);

        addQueryWrapper(queryWrapper, organizationQueryDTO, getCommonColumn());

    }

    private Map<String, SFunction<Organization, ?>> getCommonColumn() {
        return BaseEntity.getCommonColumn(
                Organization::getOrderNumber,
                Organization::getTenantId,
                Organization::getApplicationId,
                Organization::getStatus,
                Organization::getDeleted,
                Organization::getDeleteUserId,
                Organization::getDeleteTime,
                Organization::getRemark,
                Organization::getCreateUserId,
                Organization::getCreateTime,
                Organization::getUpdateUserId,
                Organization::getUpdateTime,
                Organization::getExtend1,
                Organization::getExtend2,
                Organization::getExtend3);
    }

}
